import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载Iris数据集
iris = datasets.load_iris()

# 提取sepal length和sepal width两个属性
X = iris.data[:, :2]
y = iris.target

# 选择前两类样本（Setosa和Versicolor），标签为0和1
X = X[y != 2]
y = y[y != 2]

# 每一类取前30个样本作为训练集，剩余的20个样本作为测试集
# Setosa和Versicolor各有50个样本，所以前60个样本为训练集，后40个样本为测试集
train_size = 30 * 2  # 前两类每类30个样本，共60个样本作为训练集
train_X = X[:train_size]
train_y = y[:train_size]
test_X = X[train_size:]
test_y = y[train_size:]

# 训练支持向量机（SVM）进行二分类实验
svm_model = SVC(kernel='linear')  # 使用线性核
svm_model.fit(train_X, train_y)

# 使用测试集进行预测
y_pred = svm_model.predict(test_X)

# 评估模型性能
accuracy = accuracy_score(test_y, y_pred)
print(f'Accuracy: {accuracy:.2f}')